package cn.b.sky.mes.hr.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.b.sky.mes.hr.dao.WorkCenterPerformanceDao;
import cn.b.sky.mes.hr.model.condition.PerformanceCondition;
import cn.b.sky.mes.hr.service.WorkCenterPerformanceService;

@Service
public class WorkCenterPerformanceServiceImpl implements WorkCenterPerformanceService {

  @Autowired
  private WorkCenterPerformanceDao workCenterPerformanceDao;

  private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

  @Override
  public Double personnelInOutRatioSomeDay(String siteCode, String workCenterCode, String personnelCode, String date,
      String materialCode) {
    return workCenterPerformanceDao.personnelInOutRatioSomeDay(siteCode, workCenterCode, personnelCode, date,
        materialCode);
  }

  @Override
  public Double workCenterInOutRatioSomeDay(String siteCode, String workCenterCode, String date, String materialCode) {
    List<String> personnelCodes = workCenterPerformanceDao.getPersonnelCodeListByCondition(siteCode, workCenterCode,
        date, materialCode);

    if (personnelCodes == null || personnelCodes.isEmpty()) {
      return 0.0;
    }
    Double numerator = 0.0;
    Double denominator = 0.0;
    for (String personnelCode : personnelCodes) {
      Double personnelRatio = personnelInOutRatioSomeDay(siteCode, workCenterCode, personnelCode, date, materialCode);
      numerator += personnelRatio * personnelRatio;
      denominator += personnelRatio;
    }
    if (denominator == 0) {
      return 0.0;
    }
    return numerator / denominator;
  }

  @Override
  public PerformanceCondition initDateAndWorkCenterCode(PerformanceCondition condition) {

    String minTime = condition.getMinCreateDateTime();
    String maxTime = condition.getMaxCreateDateTime();
    if (minTime == null || minTime.isEmpty() || maxTime == null || maxTime.isEmpty()) {
      Date now = new Date();
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(now);
      calendar.add(Calendar.DAY_OF_MONTH, -6);

      condition.setMaxCreateDateTime(sdf.format(now));
      condition.setMinCreateDateTime(sdf.format(calendar.getTime()));
    }
    return condition;
  }
}
